// components/postFooter/postFooter.js

import fetch from "../../utils/fetch";
import {gotoLogin} from '../../utils/util';

const globalData = getApp().globalData;

const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    post:{
      type:Object,
      value:{}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    isLike: 0,   //是否点赞了动态,
    liked:true,  //用于防止重复点赞
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //文章点赞功能
    changeLiked:function(e){
      if(!globalData.isLogin){
        gotoLogin();
        return ;
      }
      if(!this.data.liked){
        wx.showToast({
          title: '点赞操作过于频繁，请稍后再点赞',
          icon:'none'
        })
        return;
      }
      this.data.liked = false;

      var that = this;
      const originPost = Object.assign({},this.data.post);
      const post = this.data.post;
      let likePromise;    //用来存放点赞成功或则取消点赞的Promise，然后执行响应的回调
      if(post.likeStatus){
        post.likeStatus = false;
        post.likeNum--;
        likePromise = this.deleteLiked(post.id,post.user.id);
      }
      else{
        post.likeStatus = true;
        post.likeNum++;
        likePromise = this.successLiked(post.id,post.user.id);
      }

      this.setData({
        isLike:1,
        post:post
      });

      //实现动画点赞
      setTimeout(()=>{
        this.setData({
          isLike:0,
        });
      },500);

      //执行点赞返回的回调
      likePromise.then(result=>{
        wx.showToast({
          title: post.likeStatus ? '点赞成功':'取消点赞',
          duration: 1000,
          mask: true,
          icon: 'success'
        });
        that.data.liked = true;
      })
      .catch(err=>{
        console.log(err);
        that.setData({
          post:originPost
        });
        wx.showToast({
          title: '点赞失败',
          duration: 1000,
          mask: true,
          icon: 'error'
        });
        that.data.liked = true;
      })
    },

    //取消点赞
    deleteLiked:function(postId,authorId){
      return fetch('/post/dislike',{
        userId:globalData.userInfo.id,
        postId,
        authorId
      })
    },


    //成功点赞
    successLiked:function(postId,authorId){
      return fetch('/post/like',{
        userId:globalData.userInfo.id,
        postId,
        authorId,
      })
    },

  }
})
